import os
import io
from publishutilitie import publishutilitie
class logutilitie:
    
    LogFilePath = os.path.join(os.getcwd(),'logs')
    
    def __init__(self,logInputDirName='default',LogFilePath='',clearDir = True,encoding='utf-8'):
        if(len(LogFilePath) == 0):
            LogFilePath = self.LogFilePath
        LogFilePath = os.path.join(LogFilePath,logInputDirName)
        if(clearDir == True):
            if(os.path.isdir(LogFilePath)):
                for root, dirs, files in os.walk(LogFilePath, topdown=False):
                    for name in files:
                        os.remove(os.path.join(root, name))
                    for name in dirs:
                        os.rmdir(os.path.join(root, name))
            else:
                os.mkdir(LogFilePath)
        self.LogFilePath = LogFilePath
        
    def wirteLog(self,logName,contentLog):
        filePath = os.path.join(self.LogFilePath,logName)
        dirPath,fileName = os.path.split(filePath);
        if (os.path.exists(dirPath) == False):
            os.makedirs(dirPath)
        writeType = 'a'
        if(not os.path.isfile(filePath)):
            writeType = 'w'
        if(isinstance(contentLog,(list,set))):
            with open(filePath,writeType,encoding='utf-8') as f:
                for log in contentLog :
                    log = ('%s\n' % log)
                    f.write(log)
        else:
            contentLog = ('%s\n' % (contentLog))
            with open(filePath,writeType,encoding='utf-8') as f:
                f.write(contentLog)
            
    #----------------------------------------------------------------------
    def readLogToList(self,logName):
        """"""
        lineList = []
        filePath = os.path.join(self.LogFilePath,logName)
        if(os.path.isfile(filePath)):
            writeType = 'rt'
            f = open(filePath,writeType,encoding='utf-8')
            line = f.readline() 
            while line:
                lineList = lineList + [line]
                line = f.readline() 
        return lineList
    
    def removeFile(self,pFilePath,cDirPath='over',cFileName=''):
        import shutil
        if(os.path.exists(pFilePath) == False):
            return False
        pDirPath,pFileName = os.path.split(pFilePath);
        if(cFileName == ''):
            cFileName = pFileName
        if(cDirPath == 'over'):
            cDirPath = os.path.join(self.LogFilePath,cDirPath)
        cFilePath = os.path.join(cDirPath,cFileName)
        if (os.path.exists(cDirPath) == False):
            os.makedirs(cDirPath)      
        shutil.move(pFilePath,cFilePath)
        return True
            